/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.func.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.func.funcPerm.ControlFieldAuthVo;
import com.je.common.base.func.funcPerm.fastAuth.CustomerFuncPerm;
import com.je.common.base.func.funcPerm.fastAuth.FastAuthVo;
import com.je.common.base.func.funcPerm.fastAuth.FuncQuickPermission;
import com.je.common.base.func.funcPerm.roleSqlAuth.RoleSqlAuthScopeVo;
import com.je.common.base.func.funcPerm.roleSqlAuth.RoleSqlAuthVo;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.QueryBuilderService;
import com.je.common.base.util.JEUUID;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.cache.funcperm.RoleSqlAuthCache;
import com.je.meta.constant.FuncDataPermCons;
import com.je.meta.rpc.func.MetaFuncPermService;
import com.je.meta.service.func.CustomerFuncPermService;
import com.je.meta.service.permission.*;
import com.je.meta.util.DataPermUtils;
import com.je.rbac.rpc.DepartmentUserRpcService;
import com.je.rbac.rpc.RoleRpcService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class CustomerFuncPermServiceImpl implements CustomerFuncPermService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private RoleRpcService roleRpcService;
    @Autowired
    private QueryBuilderService queryBuilderService;
    @Autowired
    private MetaFuncPermService metaFuncPermService;
    @Autowired
    private PcFuncSelfDataService pcFuncSelfDataService;
    @Autowired
    private PcFuncDeptLeaderDataService pcFuncDeptLeaderDataService;
    @Autowired
    private PcFuncDirectLeaderDataService pcFuncDirectLeaderDataService;
    @Autowired
    private PcFuncMyDeptDataService pcFuncMyDeptDataService;
    @Autowired
    private PcFuncMonitorLeaderDataService pcFuncMonitorLeaderDataService;
    @Autowired
    private PcFuncMonitorCompanyDataService pcFuncMonitorCompanyDataService;
    @Autowired
    private PcFuncDeptMonitorDeptDataService pcFuncDeptMonitorDeptDataService;
    @Autowired
    private PcFuncCompanyDataService pcFuncCompanyDataService;
    @Autowired
    private PcFuncGroupCompanyDataService pcFuncGroupCompanyDataService;
    @Autowired
    private PcFuncMyApprovePendingDataService pcFuncMyApprovePendingDataService;
    @Autowired
    private PcFuncMyApprovePendedDataService pcFuncMyApprovePendedDataService;
    @Autowired
    private DepartmentUserRpcService departmentUserRpcService;
    @Autowired
    private RoleSqlAuthCache roleSqlAuthCache;

    @Override
    @Transactional
    public DynaBean doUpdatePerm(DynaBean dynaBean) {
        String funcId = dynaBean.getStr("FUNCPERM_FUNCINFO_ID");
        String funcpermType = dynaBean.getStr("FUNCPERM_TYPE");
        String coverValue = dynaBean.getStr("FUNCPERM_COVER_VALUE");
        DynaBean funcPerm = metaService.selectOne("JE_CORE_CUSTOMER_FUNCPERM", ConditionsWrapper.builder().eq("FUNCPERM_FUNCINFO_ID", funcId).eq("FUNCPERM_TYPE", funcpermType));

        if (funcPerm == null) {
            String id = JEUUID.uuid();
            dynaBean.setStr("JE_CORE_CUSTOMER_FUNCPERM_ID", id);
            commonService.buildModelCreateInfo(dynaBean);
            String FUNCPERM_CONFIG = dynaBean.getStr("FUNCPERM_CONFIG");
            if ("roleSqlAuth".equals(funcpermType)) {
                dynaBean.setStr("FUNCPERM_CONFIG", "");
            }
            metaService.insert(dynaBean);
            saveOrUpdateChildTable(FUNCPERM_CONFIG, id, funcpermType);
        } else {
            dynaBean.setStr("JE_CORE_CUSTOMER_FUNCPERM_ID", funcPerm.getStr("JE_CORE_CUSTOMER_FUNCPERM_ID"));
            if ("dictionaryAuth".equals(funcpermType) || "roleSqlAuth".equals(funcpermType) || "fieldAuth".equals(funcpermType)) {
                saveOrUpdateChildTable(dynaBean.getStr("FUNCPERM_CONFIG"), funcPerm.getStr("JE_CORE_CUSTOMER_FUNCPERM_ID"), funcpermType);
                dynaBean.setStr("FUNCPERM_CONFIG", "");
            }
            commonService.buildModelModifyInfo(dynaBean);
            metaService.update(dynaBean);
        }

        metaService.executeSql("UPDATE JE_CORE_CUSTOMER_FUNCPERM SET FUNCPERM_COVER_VALUE={0} WHERE FUNCPERM_FUNCINFO_ID={1}", coverValue, funcId);
        dynaBean.setStr("FUNCPERM_COVER_VALUE", coverValue);

        return dynaBean;
    }


    private void saveOrUpdateChildTable(String funcpermConfig, String parentId, String funcpermType) {
        if ("roleSqlAuth".equals(funcpermType)) {
            RoleSqlAuthVo roleSqlAuthVo = JSON.parseObject(funcpermConfig, RoleSqlAuthVo.class);
            List<RoleSqlAuthScopeVo> deptList = roleSqlAuthVo.getRoleSqlAuthDeptList();
            if (deptList != null && deptList.size() > 0) {
                for (RoleSqlAuthScopeVo dept : deptList) {
                    saveRoleSqlChildData(dept, funcpermType, parentId, "dept");
                }
            }

            List<RoleSqlAuthScopeVo> orgList = roleSqlAuthVo.getRoleSqlAuthOrgList();
            if (orgList != null && orgList.size() > 0) {
                for (RoleSqlAuthScopeVo org : orgList) {
                    saveRoleSqlChildData(org, funcpermType, parentId, "org");
                }
            }
            List<RoleSqlAuthScopeVo> roleList = roleSqlAuthVo.getRoleSqlAuthRoleList();
            if (roleList != null && roleList.size() > 0) {
                for (RoleSqlAuthScopeVo role : roleList) {
                    saveRoleSqlChildData(role, funcpermType, parentId, "role");
                }
            }

        }
    }

    private void saveRoleSqlChildData(RoleSqlAuthScopeVo roleSqlAuthScopeVo, String funcpermType, String parentId, String dataType) {
        DynaBean dynaBean = new DynaBean("JE_CORE_CUSTOMER_FUNCPERM_CONFIG", true);
        DynaBean config = metaService.selectOne("JE_CORE_CUSTOMER_FUNCPERM_CONFIG", ConditionsWrapper.builder().eq("CONFIG_DATA_ID", roleSqlAuthScopeVo.getId()).eq("CONFIG_PERM_TYPE", funcpermType).eq("CONFIG_FUNCPERM_ID", parentId));
        if (config == null) {
            dynaBean.setStr("CONFIG_FUNCPERM_ID", parentId);
            dynaBean.setStr("CONFIG_TYPE", dataType);
            dynaBean.set("CONFIG_INFO", JSON.toJSONString(roleSqlAuthScopeVo));
            dynaBean.setStr("CONFIG_DATA_ID", roleSqlAuthScopeVo.getId());
            dynaBean.setStr("CONFIG_PERM_TYPE", funcpermType);
            commonService.buildModelCreateInfo(dynaBean);
            metaService.insert(dynaBean);
        } else {
            dynaBean.setStr("JE_CORE_CUSTOMER_FUNCPERM_CONFIG_ID", config.getStr("JE_CORE_CUSTOMER_FUNCPERM_CONFIG_ID"));
            dynaBean.set("CONFIG_INFO", JSON.toJSONString(roleSqlAuthScopeVo));
            commonService.buildModelModifyInfo(dynaBean);
            metaService.update(dynaBean);
        }
    }

    @Override
    public List<DynaBean> getPermData(DynaBean dynaBean) {
        String FUNCPERM_TYPE = dynaBean.getStr("FUNCPERM_TYPE");
        String type = dynaBean.getStr("type");
        ConditionsWrapper conditionsWrapper = ConditionsWrapper.builder();
        conditionsWrapper.eq("FUNCPERM_FUNCINFO_ID", dynaBean.getStr("FUNCPERM_FUNCINFO_ID"));
        if (StringUtils.isNotEmpty(FUNCPERM_TYPE)) {
            conditionsWrapper.eq("FUNCPERM_TYPE", dynaBean.getStr("FUNCPERM_TYPE"));
        }
        //如果是租户则增加租户条件
        if ("ZH".equals(type)) {
            conditionsWrapper.eq("SY_TENANT_ID", SecurityUserHolder.getCurrentAccountTenantId());
        }
        List<DynaBean> authList = metaService.select("JE_CORE_CUSTOMER_FUNCPERM", conditionsWrapper);
        if (authList != null && authList.size() > 0) {
            for (DynaBean authItem : authList) {
                String itemType = authItem.getStr("FUNCPERM_TYPE");
                if ("roleSqlAuth".equals(itemType)) {
                    String JE_CORE_CUSTOMER_FUNCPERM_ID = authItem.getStr("JE_CORE_CUSTOMER_FUNCPERM_ID");
                    List<DynaBean> dataList = metaService.select("JE_CORE_CUSTOMER_FUNCPERM_CONFIG", ConditionsWrapper.builder().eq("CONFIG_FUNCPERM_ID", JE_CORE_CUSTOMER_FUNCPERM_ID));
                    //角色sql授权
                    RoleSqlAuthVo roleSqlAuthVo = new RoleSqlAuthVo();
                    List<RoleSqlAuthScopeVo> deptRoleSql = new ArrayList<>();
                    roleSqlAuthVo.setRoleSqlAuthDeptList(deptRoleSql);
                    List<RoleSqlAuthScopeVo> orgRoleSql = new ArrayList<>();
                    roleSqlAuthVo.setRoleSqlAuthOrgList(orgRoleSql);
                    List<RoleSqlAuthScopeVo> roleRoleSql = new ArrayList<>();
                    roleSqlAuthVo.setRoleSqlAuthRoleList(roleRoleSql);
                    //字段授权
                    for (DynaBean data : dataList) {
                        String dataType = data.getStr("CONFIG_TYPE");
                        String dataId = data.getStr("CONFIG_DATA_ID");
                        String configInfo = data.getStr("CONFIG_INFO");
                        if ("roleSqlAuth".equals(itemType)) {
                            RoleSqlAuthScopeVo roleSqlAuthScopeVo = new RoleSqlAuthScopeVo();
                            roleSqlAuthScopeVo.setId(dataId);
                            JSONObject jsonObject = JSON.parseObject(configInfo);
                            roleSqlAuthScopeVo.setSql(jsonObject.getString("sql"));
                            roleSqlAuthScopeVo.setCoverSql(jsonObject.getString("coverSql"));
                            if ("org".equals(dataType)) {
                                orgRoleSql.add(roleSqlAuthScopeVo);
                            }
                            if ("dept".equals(dataType)) {
                                deptRoleSql.add(roleSqlAuthScopeVo);
                            }
                            if ("role".equals(dataType)) {
                                roleRoleSql.add(roleSqlAuthScopeVo);
                            }
                        }
                    }
                    if ("roleSqlAuth".equals(itemType)) {
                        authItem.set("FUNCPERM_CONFIG", JSON.toJSONString(roleSqlAuthVo));
                    }
                }
                buildRetureData(itemType, authItem, dynaBean);
                if (Strings.isNullOrEmpty(authItem.getStr("FUNCPERM_COVER_VALUE"))) {
                    authItem.setStr("FUNCPERM_COVER_VALUE", "and");
                }
            }
        } else {
            List<DynaBean> list = metaService.select("JE_CORE_CUSTOMER_FUNCPERM", ConditionsWrapper.builder().eq("FUNCPERM_FUNCINFO_ID", dynaBean.getStr("FUNCPERM_FUNCINFO_ID")));
            String coverValue = "and";
            if (list.size() > 0) {
                if (!Strings.isNullOrEmpty(list.get(0).getStr("FUNCPERM_COVER_VALUE"))) {
                    coverValue = list.get(0).getStr("FUNCPERM_COVER_VALUE");
                }
            }
            DynaBean authItem = new DynaBean();
            buildRetureData(FUNCPERM_TYPE, authItem, dynaBean);
            authItem.setStr("FUNCPERM_COVER_VALUE", coverValue);
            authList.add(authItem);
        }
        return authList;
    }

    private void buildRetureData(String itemType, DynaBean authItem, DynaBean parm) {
        JSONTreeNode roleTree = roleRpcService.buildRoleTreeByRoleIds(null, false);
        if ("roleSqlAuth".equals(itemType)) {
            //装配角色树信息
            authItem.set("roleTree", roleTree);
        }
    }

    @Override
    public void restoreDefault(String funcCode) {
        metaService.delete("JE_CORE_CUSTOMER_FUNCPERM", ConditionsWrapper.builder().eq("FUNCPERM_FUNCINFO_CODE", funcCode));
    }

    @Override
    public FuncQuickPermission getCustomerFuncQuickPermission(String code) {
        FastAuthVo fastAuthVo;
        fastAuthVo = (FastAuthVo) getDataFromDB(code, FuncDataPermCons.FAST_AUTH);
        if (fastAuthVo != null) {
            return DataPermUtils.toFuncQuickPermission(fastAuthVo, null);
        }
        return null;
    }

    @Override
    public RoleSqlAuthVo getCustomerFuncRoleSqlPermission(String code) {
        RoleSqlAuthVo roleSqlAuthVo = (RoleSqlAuthVo) getDataFromDB(code, FuncDataPermCons.ROLESQL_AUTH);
        return roleSqlAuthVo;
    }

    @Override
    public String getCustomerFuncSqlPermission(String code) {
        String sql = (String) getDataFromDB(code, FuncDataPermCons.SQL_AUTH);
        return sql;
    }

    @Override
    public String buildCustomerFuncPermSql(CustomerFuncPerm customerFuncPerm) {
        return funcPermBuild(customerFuncPerm);
    }


    public String funcPermBuild(CustomerFuncPerm customerFuncPerm) {
        //快速授权
        String quickQuerySql = outputQuickQuerySql(customerFuncPerm.getFuncQuickPermission());
        /**
         * 角色sql授权
         * 一个人可能有多个角色
         */
        //当前账号所属的角色集合
        RoleSqlAuthVo roleSqlAuthVo = customerFuncPerm.getRoleSqlAuthVo();
        //若授权开关开启
        String finalSql = "";
        if (roleSqlAuthVo != null && "1".equals(roleSqlAuthVo.getAuthOnOff())) {
            String roleSql = "";
            String deptSql = "";
            String orgSql = "";
            List<RoleSqlAuthScopeVo> deptRoleSqlList = roleSqlAuthVo == null ? null : roleSqlAuthVo.getRoleSqlAuthDeptList();
            if (deptRoleSqlList != null && deptRoleSqlList.size() > 0) {
                String accountDepartmentId = "";
                if (SecurityUserHolder.getCurrentAccountDepartment() == null) {
                    accountDepartmentId = SecurityUserHolder.getCurrentAccountRealOrgId();
                } else {
                    accountDepartmentId = SecurityUserHolder.getCurrentAccountDepartment().getId();
                }
                for (RoleSqlAuthScopeVo roleSqlAuthScopeVo : deptRoleSqlList) {
                    String deptId = roleSqlAuthScopeVo.getId();
                    String sql = roleSqlAuthScopeVo.getSql();
                    String sqlStr = "";
                    if (accountDepartmentId != null && accountDepartmentId.equals(deptId) && StringUtil.isNotEmpty(sql)) {
                        sqlStr += queryBuilderService.trimSql(sql);
                        if (StringUtil.isEmpty(deptSql)) {
                            deptSql += "(" + sqlStr + ")";
                        } else {
                            deptSql += " OR (" + sqlStr + ")";
                        }
                    }
                }
            }
            List<RoleSqlAuthScopeVo> orgRoleSqlList = roleSqlAuthVo == null ? null : roleSqlAuthVo.getRoleSqlAuthOrgList();
            if (orgRoleSqlList != null && orgRoleSqlList.size() > 0) {
                String accountRealOrgId = SecurityUserHolder.getCurrentAccountRealOrgId();
                for (RoleSqlAuthScopeVo roleSqlAuthScopeVo : orgRoleSqlList) {
                    String orgId = roleSqlAuthScopeVo.getId();
                    String sql = roleSqlAuthScopeVo.getSql();
                    String sqlStr = "";
                    if (accountRealOrgId != null && accountRealOrgId.equals(orgId) && StringUtil.isNotEmpty(sql)) {
                        sqlStr += queryBuilderService.trimSql(sql);
                        if (StringUtil.isEmpty(orgSql)) {
                            orgSql += "(" + sqlStr + ")";
                        } else {
                            orgSql += " OR (" + sqlStr + ")";
                        }
                    }
                }
            }
            List<RoleSqlAuthScopeVo> roleRoleSqlList = roleSqlAuthVo == null ? null : roleSqlAuthVo.getRoleSqlAuthRoleList();
            if (roleRoleSqlList != null && roleRoleSqlList.size() > 0) {
                List<String> roleIds = SecurityUserHolder.getCurrentAccount().getRoleIds();
                for (RoleSqlAuthScopeVo roleSqlAuthScopeVo : roleRoleSqlList) {
                    String roleid = roleSqlAuthScopeVo.getId();
                    String sql = roleSqlAuthScopeVo.getSql();
                    String sqlStr = "";
                    if (roleIds != null && roleIds.contains(roleid) && StringUtil.isNotEmpty(sql)) {
                        sqlStr += queryBuilderService.trimSql(sql);
                        if (StringUtil.isEmpty(roleSql)) {
                            roleSql += "(" + sqlStr + ")";
                        } else {
                            roleSql += " OR (" + sqlStr + ")";
                        }
                    }
                }
            }
            if (StringUtil.isNotEmpty(roleSql)) {
                finalSql += "(" + roleSql + ")";
            }
            if (StringUtil.isNotEmpty(orgSql)) {
                if (StringUtil.isEmpty(finalSql)) {
                    finalSql += "(" + orgSql + ")";
                } else {
                    finalSql += " OR (" + orgSql + ")";
                }
            }
            if (StringUtil.isNotEmpty(deptSql)) {
                if (StringUtil.isEmpty(finalSql)) {
                    finalSql += "(" + deptSql + ")";
                } else {
                    finalSql += " OR (" + deptSql + ")";
                }
            }
        }
        String finalSql1 = finalSql;

        //sql授权
        String sqlP = customerFuncPerm.getSql();

        StringBuffer resultSqlBuffer = new StringBuffer();

        // quickQuerySql为空，有特殊含义，为1=1
        if (!Strings.isNullOrEmpty(quickQuerySql)) {
            if (!Strings.isNullOrEmpty(quickQuerySql) || !Strings.isNullOrEmpty(finalSql1) || !Strings.isNullOrEmpty(sqlP)) {
                resultSqlBuffer.append("(");
            }
            //快速授权
            if (StringUtil.isNotEmpty(quickQuerySql)) {
                resultSqlBuffer.append(queryBuilderService.trimSql(quickQuerySql));
            }
            //角色授权
            if (StringUtil.isNotEmpty(finalSql1)) {
                if (!StringUtil.isEmpty(resultSqlBuffer.toString()) && !resultSqlBuffer.toString().trim().equals("(")) {
                    resultSqlBuffer.append(" OR ");
                }
                resultSqlBuffer.append(finalSql1);
            }

            if (StringUtil.isEmpty(resultSqlBuffer.toString()) || resultSqlBuffer.toString().trim().equals("(")) {
                if (StringUtil.isNotEmpty(sqlP)) {
                    resultSqlBuffer.append(queryBuilderService.trimSql(sqlP));
                }
            } else {
                if (StringUtil.isNotEmpty(sqlP) && !resultSqlBuffer.toString().trim().equals("(")) {
                    resultSqlBuffer.append(" OR ");
                    resultSqlBuffer.append(queryBuilderService.trimSql(sqlP));
                }
            }

            if (!Strings.isNullOrEmpty(quickQuerySql) || !Strings.isNullOrEmpty(finalSql1) || !Strings.isNullOrEmpty(sqlP)) {
                resultSqlBuffer.append(")");
            }
        }
        return resultSqlBuffer.toString();
    }


    private Object getDataFromDB(String funcCode, String type) {
        DynaBean dynaBean = metaService.selectOne("JE_CORE_CUSTOMER_FUNCPERM", ConditionsWrapper.builder().eq("FUNCPERM_FUNCINFO_CODE", funcCode).eq("FUNCPERM_TYPE", type));
        List<DynaBean> list = null;
        if (dynaBean != null) {
            String FUNCPERM_ON_OFF = dynaBean.getStr("FUNCPERM_ON_OFF");
            if (FuncDataPermCons.SQL_AUTH.equals(type)) {
                return dynaBean.get("FUNCPERM_CONFIG") == null ? "" : dynaBean.get("FUNCPERM_CONFIG");
            }
            if (FuncDataPermCons.CONTROL_FIELD.equals(type)) {
                ControlFieldAuthVo controlFieldAuthVo = JSON.parseObject(dynaBean.getStr("FUNCPERM_CONFIG"), ControlFieldAuthVo.class);
                return controlFieldAuthVo;
            }
            if (FuncDataPermCons.FAST_AUTH.equals(type)) {
                FastAuthVo fastAuthVo = JSON.parseObject(dynaBean.getStr("FUNCPERM_CONFIG"), FastAuthVo.class);
                fastAuthVo.setAuthOnOff(FUNCPERM_ON_OFF);
                return fastAuthVo;
            }
            list = metaService.select("JE_CORE_CUSTOMER_FUNCPERM_CONFIG", ConditionsWrapper.builder().eq("CONFIG_FUNCPERM_ID", dynaBean.getStr("JE_CORE_CUSTOMER_FUNCPERM_ID")));

            if (FuncDataPermCons.ROLESQL_AUTH.equals(type)) {
                return DataPermUtils.toRoleSqlAuth(FUNCPERM_ON_OFF, list);
            }
        }
        return null;
    }


    public String outputQuickQuerySql(FuncQuickPermission funcQuickPermission) {
        StringBuffer sb = new StringBuffer();
        //没有开启，则直接返回
        if (funcQuickPermission == null || !funcQuickPermission.isActive() || SecurityUserHolder.getCurrentAccount() == null) {
            return null;
        }

        boolean seePriority = false;
        //可见人员
        if (funcQuickPermission.isUserControlQuery() && funcQuickPermission.getSeeUserIdList() != null
                && !funcQuickPermission.getSeeUserIdList().isEmpty()
                && funcQuickPermission.getSeeUserIdList().contains(SecurityUserHolder.getCurrentAccountRealUserId())) {
            seePriority = true;
        }

        //可见部门
        if (!seePriority && funcQuickPermission.isDeptControlQuery() && funcQuickPermission.getSeeDeptIdList() != null
                && !funcQuickPermission.getSeeDeptIdList().isEmpty()
                && funcQuickPermission.getSeeDeptIdList().contains(SecurityUserHolder.getCurrentAccountRealOrgId())) {
            seePriority = true;
        }

        //可见角色
        if (!seePriority && funcQuickPermission.isRoleControlQuery()) {
            List<String> userIdList = roleRpcService.findRoleUserIds(funcQuickPermission.getSeeRoleIdList());
            if (userIdList != null && !userIdList.isEmpty() && userIdList.contains(SecurityUserHolder.getCurrentAccountRealUserId())) {
                seePriority = true;
            }
        }

        //可见机构
        if (!seePriority && funcQuickPermission.isOrgControlQuery()) {
            if (funcQuickPermission.getSeeOrgIdList() != null && !funcQuickPermission.getSeeOrgIdList().isEmpty()
                    && funcQuickPermission.getSeeOrgIdList().contains(SecurityUserHolder.getCurrentAccount().getPlatformOrganization().getId())) {
                seePriority = true;
            }
        }

        if (seePriority) {
            return "";
        }

        sb.append(pcFuncSelfDataService.formatFuncDataSelfShowOutput(funcQuickPermission.getCreateUserIdField(), SecurityUserHolder.getCurrentAccountRealUserId()));
        //部门领导
        if (funcQuickPermission.isDeptHeadQuery()) {
            List<String> majorList = departmentUserRpcService.findDeptLeaderIds(SecurityUserHolder.getCurrentAccountRealOrgId());
            if (majorList != null && majorList.contains(SecurityUserHolder.getCurrentAccountRealUserId())) {
                sb.append(" OR ");
                sb.append(pcFuncDeptLeaderDataService.formatFuncDataDeptLeaderShowOutput(funcQuickPermission.getCreateDeptIdField(), SecurityUserHolder.getCurrentAccountRealOrgId()));
            }
        }

        //直接领导
        if (funcQuickPermission.isDirectLeaderQuery()) {
            List<String> userIdList = departmentUserRpcService.findDirectUserIds(SecurityUserHolder.getCurrentAccountRealOrgId(), SecurityUserHolder.getCurrentAccountRealUserId());
            if (userIdList != null && !userIdList.isEmpty() && !Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccountRealOrgId())) {
                sb.append(" OR ");
                sb.append(pcFuncDirectLeaderDataService.formatFuncDataDirectLeaderShowOutput(funcQuickPermission.getCreateDeptIdField(), funcQuickPermission.getCreateUserIdField(), SecurityUserHolder.getCurrentAccountRealOrgId(), userIdList));
            }
        }

        //本部门
        if (funcQuickPermission.isMyDeptQuery()) {
            if (!Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccountRealOrgId())) {
                sb.append(" OR ");
                sb.append(pcFuncMyDeptDataService.formatFuncDataMyDeptShowOutput(funcQuickPermission.getCreateDeptIdField(), SecurityUserHolder.getCurrentAccountRealOrgId()));
            }
        }

        //监管领导
        if (funcQuickPermission.isMonitorLeaderQuery() && SecurityUserHolder.getCurrentAccountRealDepartmentUser() != null) {
            List<String> monitDeptList = departmentUserRpcService.findMonitorDeptIds(SecurityUserHolder.getCurrentAccountRealOrgId(), SecurityUserHolder.getCurrentAccountRealUserId());
            if (monitDeptList != null && !monitDeptList.isEmpty()) {
                sb.append(" OR ");
                sb.append(pcFuncMonitorLeaderDataService.formatFuncDataMonitorLeaderShowOutput(funcQuickPermission.getCreateDeptIdField(), monitDeptList));
            }
        }

        //部门间监管
        if (funcQuickPermission.isDeptMonitorDeptQuery() && SecurityUserHolder.getCurrentAccountDepartment() != null) {
            List<String> deptMonitorDeptIdList = departmentUserRpcService.findDeptMonitorDeptIds(SecurityUserHolder.getCurrentAccountRealOrgId());
            if (deptMonitorDeptIdList != null && !deptMonitorDeptIdList.isEmpty()) {
                sb.append(" OR ");
                sb.append(pcFuncDeptMonitorDeptDataService.formatFuncDataDeptMonitorDeptShowOutput(funcQuickPermission.getCreateDeptIdField(), deptMonitorDeptIdList));
            }
        }

        //公司内
        if (funcQuickPermission.isMyCompanyQuery() && SecurityUserHolder.getCurrentAccountDepartment() != null) {
            if (SecurityUserHolder.getCurrentAccountDepartment() != null && !Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccountDepartment().getCompanyId())) {
                sb.append(" OR ");
                sb.append(pcFuncCompanyDataService.formatFuncDataCompanyShowOutput(funcQuickPermission.getCompanyIdFieldCode(), SecurityUserHolder.getCurrentAccountDepartment().getCompanyId()));
            }
        }

        //集团公司内可见
        if (funcQuickPermission.isGroupCompanyQuery() && SecurityUserHolder.getCurrentAccountDepartment() != null) {
            if (SecurityUserHolder.getCurrentAccountDepartment() != null && !Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccountDepartment().getGroupCompanyId())) {
                sb.append(" OR ");
                sb.append(pcFuncGroupCompanyDataService.formatFuncDataGroupCompanyShowOutput(funcQuickPermission.getGroupCompanyIdFieldCode(), SecurityUserHolder.getCurrentAccountDepartment().getGroupCompanyId()));
            }
        }

        //公司监管
        if (funcQuickPermission.isMonitorCompanyQuery() && SecurityUserHolder.getCurrentAccountRealDepartmentUser() != null) {
            if (SecurityUserHolder.getCurrentAccountDepartment() != null && !Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccountDepartment().getCompanyId())) {
                List<String> companyMonitorCompanyIds = departmentUserRpcService.findCompanyMonitorCompanyIds(SecurityUserHolder.getCurrentAccountDepartment().getCompanyId());
                if (companyMonitorCompanyIds != null && !companyMonitorCompanyIds.isEmpty()) {
                    sb.append(" OR ");
                    sb.append(pcFuncMonitorCompanyDataService.formatFuncDataMonitorCompanyShowOutput(funcQuickPermission.getCompanyIdFieldCode(), companyMonitorCompanyIds));
                }
            }
        }

        //待审批可见
        if (funcQuickPermission.isApproPreQuery()) {
            if (!Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccount().getDeptId())) {
                sb.append(" OR ");
                sb.append(pcFuncMyApprovePendingDataService.formatFuncDataMyApprovePendingShowOutout(SecurityUserHolder.getCurrentAccount().getDeptId()));
            }
        }

        //审批后可见
        if (funcQuickPermission.isApproAfterQuery()) {
            if (!Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccount().getDeptId())) {
                sb.append(" OR ");
                sb.append(pcFuncMyApprovePendedDataService.formatFuncDataMyApprovePendedShowOutput(SecurityUserHolder.getCurrentAccount().getDeptId()));
            }
        }

        String whereSql = sb.toString();
        if (StringUtil.isNotEmpty(whereSql)) {
            if (whereSql.trim().startsWith("OR")) {
                whereSql = whereSql.trim().replaceFirst("OR", "");
            }
        }
        return whereSql;
    }


}
